package com.aizu.utils;

import java.io.*;
import java.net.*;

import org.apache.log4j.Logger;

/**
 * 短信工具类
 */
public class SmsUtils {

	private static Logger logger = Logger.getLogger(SmsUtils.class);

	/**
	 * 发送短信
	 * 
	 * @param phone
	 *            接收者手机号
	 * @param content
	 *            发送内容
	 * @return
	 * @throws IOException
	 */
	public static String sendSms(String phone, String content)
			throws IOException {
		logger.info("接收短信手机号: " + phone + "，内容: " + content);
		return HttpSend.getInstance().send(phone, content);
	}

}

/**
 * webservice发送短信<br />
 * 参考 http://www.1xinxi.cn/quotation.aspx
 */
final class HttpSend {

	private Logger logger = Logger.getLogger(this.getClass());

	private static HttpSend httpSend;

	private synchronized static void newInstance() {
		if (null == httpSend) {
			httpSend = new HttpSend();
		}
	}

	public static HttpSend getInstance() {
		if (null == httpSend) {
			newInstance();
		}
		return httpSend;
	}

	/**
	 * @param phone
	 *            接收者手机号
	 * @param content
	 *            发送内容
	 * @return
	 * @throws IOException
	 */
	public String send(String phone, String content) throws IOException {
		// 发送内容
		String sign = "云i租";

		// 创建StringBuffer对象用来操作字符串
		StringBuffer sb = new StringBuffer(
				"http://sms.1xinxi.cn/asmx/smsservice.aspx?");

		// 向StringBuffer追加用户名
		sb.append("name=yuwei_thank1983@163.com");

		// 向StringBuffer追加密码（登陆网页版，在管理中心--基本资料--接口密码，是28位的）
		sb.append("&pwd=03834D85A08A3B60A9F05D09C135");

		// 向StringBuffer追加手机号码
		sb.append("&mobile=").append(phone);

		// 向StringBuffer追加消息内容转URL标准码
		sb.append("&content=" + URLEncoder.encode(content, "UTF-8"));

		// 追加发送时间，可为空，为空为及时发送
		sb.append("&stime=");

		// 加签名
		sb.append("&sign=" + URLEncoder.encode(sign, "UTF-8"));

		// type为固定值pt extno为扩展码，必须为数字 可为空
		sb.append("&type=pt&extno=");
		// 创建url对象
		// String temp = new String(sb.toString().getBytes("GBK"),"UTF-8");
		logger.info(sb.toString());
		URL url = new URL(sb.toString());

		// 打开url连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		// 设置url请求方式 ‘get’ 或者 ‘post’
		connection.setRequestMethod("POST");

		// 发送
		InputStream is = url.openStream();

		// 转换返回值
		String returnStr = convertStreamToString(is);

		// 释放连接
		connection.disconnect();

		// 返回结果为‘0，20140009090990,1，提交成功’ 发送成功 具体见说明文档
		logger.info(returnStr);
		// 返回发送结果

		return returnStr;
	}

	/**
	 * 转换返回值类型为UTF-8格式.
	 * 
	 * @param is
	 * @return
	 */
	public String convertStreamToString(InputStream is) {
		StringBuilder sb1 = new StringBuilder();
		byte[] bytes = new byte[4096];
		int size = 0;

		try {
			while ((size = is.read(bytes)) > 0) {
				String str = new String(bytes, 0, size, "UTF-8");
				sb1.append(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb1.toString();
	}
}
